﻿using System;
using System.IO;
using UnityEngine;

namespace XUBuilder
{
    namespace Editor
    {
        public class XUBuilderUtil
        {
            public static string GetSizeString(long fileSize)
            {
                if (fileSize >= (1024 * 1024))
                {
                    return string.Format("{0:F2}MB", fileSize * 1f / (1024 * 1024));
                }
                else
                {
                    return string.Format("{0:F2}KB", fileSize * 1f / 1024);
                }
            }

            //=================================================================================

            public static void EnsureFolder(string folder)
            {
                string fullName = folder;
                if (File.Exists(folder))
                {
                    fullName = Path.GetDirectoryName(folder);
                }
                if (!Directory.Exists(fullName))
                {
                    Directory.CreateDirectory(fullName);
                }
            }

            public static bool ClearFolder(string folder, bool deleteSelf)
            {
                try
                {
                    if (string.IsNullOrEmpty(folder) || !Directory.Exists(folder))
                    {
                        return true;  // 如果参数为空，则视为已成功清空
                    }
                    // 删除当前文件夹下所有文件
                    foreach (string strFile in Directory.GetFiles(folder))
                    {
                        File.Delete(strFile);
                    }
                    // 删除当前文件夹下所有子文件夹(递归)
                    foreach (string strDir in Directory.GetDirectories(folder))
                    {
                        Directory.Delete(strDir, true);
                    }
                    // 删除自身
                    if (deleteSelf)
                    {
                        Directory.Delete(folder);
                    }
                    return true;
                }
                catch (Exception ex)
                {
                    Debug.LogError(string.Format("清空 {0} 异常\n消息:{1}\n堆栈:{2}", folder, ex.Message, ex.StackTrace));
                    return false;
                }
            }
        }
    }
}